import { Router, RouteRecordRaw } from 'vue-router'
import { getToken, removeToken } from '@/utils/auth'
import store from '@/store'
import { ResponseCode } from '@/enums/httpEnum'

// 路由白名单
const whiteList = ['/login', '/404']

/**
 * 创建路由守卫，权限控制
 * @param router 
 */
export function createRouterGuards(router: Router) {

  // 路由权限校验
  router.beforeEach(async (to, from, next) => {
    if(getToken()) {
      if(to.path === '/login') {
        next('/')
        return
      } else {
        const hasRole = store.getters.roles && store.getters.roles.length > 0
        if(hasRole) {
          next()
          return
        } else {
          store.dispatch('user/GetUserInfo')
          store.dispatch('app/GetGenderOption')
          store.dispatch('app/GetStatusOption')
          // if(result.code !== ResponseCode.SUCCESS) {
          //   removeToken()
          //   next('/login')
          //   return
          // }
          const result2 = await store.dispatch('route/GenerateRoutes')
          console.log('result2', result2)
          result2.forEach(item => {
            router.addRoute(item as unknown as RouteRecordRaw)
          });

          // todo：待完善
          next({ ...to, replace: true })
          // const nextPath = to.path ? 
          return
        }
      }
    } else {
      if(whiteList.includes(to.path)) {
        next()
        return
      } else {
        if(to.path === '/index') {
          next('/login')
          return
        } else {
          next(`/login?redirect=${to.path}`)
          return
        }
      }
    }
  })


  // 隐藏progressBar
  router.afterEach((to) => {
    const keepAliveComponents = store.getters.keepAliveComponents
    const currentComponentName = to.matched.find(item => item.name == to.name)?.name
    if(currentComponentName && !keepAliveComponents.includes(currentComponentName) && to.meta.keepAlive) {
      keepAliveComponents.push(currentComponentName)
    }
    store.dispatch('route/SetKeepAliveComponents', keepAliveComponents)
    // 进度条结束
  })
}
